package com.exe.rege.filter;


import com.alibaba.fastjson.JSON;
import com.exe.rege.common.BaseContext;
import com.exe.rege.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
* 过滤器判断是否用户正常登录
* 否则直接复制url还能进入网页
* */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")//urlPatterns = "/*"指拦截所有路径
public class LoginCheckFilter implements Filter {
    //路径配置器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1、获取本次请求的url
        String requestURI = request.getRequestURI();

        log.info("拦截到请求：{}",requestURI);


        //定义不需要拦截的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",//可以访问页面资源，操作不了
                "/front/**",//这些通配符为了能找到路径配齐，需要配置通配符路径配置器
                "/common/**"//上传下载
        };

        //2、判断本次请求是否需要处理，即是否放行此路径，用check方法
        boolean check = check(urls, requestURI);

        //3、如果不需要处理则直接放行进入页面
        if (check){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));
            filterChain.doFilter(request, response);//过滤放行
            return;
        }

        //4、判断登录状态，如果已经登录（有session），则直接放行
        if (request.getSession().getAttribute("employee") != null){
            log.info("本次请求{}不需要处理",requestURI);

            //在此处获取当前登录用户id,放入工具类
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request, response);//过滤放行
            return;
        }

        //5、剩下未登录的情况，则通过输出流方式向客户端页面响应数据（前端需要NOTLOGIN返回，前端收到此信号则返回登录界面）
        log.info("员工未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /*
        设置好路径配置器后，还要加方法
        检查本次路径是否放行
    */
    public boolean check(String[] urls, String requestURI){

        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
